﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.InteropServices;
using RakNet;
using System.IO;
using System.Windows.Forms;
using MMOEng.Components;

namespace MMOEng.Packets.EnginePackets
{
    [Serializable]
    public class DeltaUpdateP : IPacket
    {
        public guid EntityId { get; private set; }
        public Type ComponentType { get; private set; }
        public BaseComponent Component { get; private set; }

        public DeltaUpdateP(guid id, Type componentType, BaseComponent baseC)
        {
            EntityId = id;
            ComponentType = componentType;
            Component = baseC;
        }

        public static int CreateFlag(int singleItem)
        {
            return (1 << singleItem);
        }

        public static int CreateFlag()
        {
            return -1;
        }

        public static int CreateFlag(int[] items){
            int f = 0;
            foreach(int i in items){
                f = f | (1 << i);
            }
            return f;
        }

        public RakNet.PacketPriority writePacket(RakNet.BitStream stream, out RakNet.PacketReliability pr)
        {
            BinaryFormatter f = new BinaryFormatter();
            MemoryStream m = new MemoryStream();
            f.Serialize(m, this);
            
            pr = RakNet.PacketReliability.RELIABLE;
            stream.Write((byte)PacketType.P_DELTAU);
            stream.Write(m.GetBuffer(),(uint)m.Length);
            return RakNet.PacketPriority.IMMEDIATE_PRIORITY;
        }

        public static void readPacket(MMOGame game, byte[] data)
        {
            BinaryFormatter f = new BinaryFormatter();
            MemoryStream m = new MemoryStream(data);
            DeltaUpdateP p = f.Deserialize(m) as DeltaUpdateP;
            game.SubSystemsManager.RouteCallback(p);
        }
    }
}
